<template>
  <div class="pet-health-container">
    <div class="page-header">
      <h1>🩺 宠物健康档案</h1>
      <p>关注爱宠健康，记录每一次成长</p>
    </div>

    <!-- 选择宠物 -->
    <el-card class="pet-selector-card">
      <el-radio-group v-model="selectedPetId" @change="loadHealthRecords">
        <el-radio-button v-for="pet in myPets" :key="pet.id" :label="pet.id">
          <i class="el-icon-sunrise"></i> {{ pet.name }} ({{ pet.breed }})
        </el-radio-button>
      </el-radio-group>
    </el-card>

    <!-- 健康档案概览 -->
    <el-row :gutter="20" v-if="selectedPetId">
      <el-col :span="6">
        <el-card class="info-card">
          <div class="info-content">
            <i class="el-icon-document info-icon" style="color: #409EFF"></i>
            <div>
              <div class="info-value">{{ healthSummary.totalRecords }}</div>
              <div class="info-label">总检测次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="info-card">
          <div class="info-content">
            <i class="el-icon-date info-icon" style="color: #67C23A"></i>
            <div>
              <div class="info-value">{{ healthSummary.lastCheckDate }}</div>
              <div class="info-label">最近检测</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="info-card">
          <div class="info-content">
            <i class="el-icon-trophy info-icon" style="color: #E6A23C"></i>
            <div>
              <div class="info-value">{{ healthSummary.healthScore }}</div>
              <div class="info-label">健康评分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="info-card">
          <div class="info-content">
            <i class="el-icon-warning info-icon" style="color: #F56C6C"></i>
            <div>
              <div class="info-value">{{ healthSummary.abnormalItems }}</div>
              <div class="info-label">异常项</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 健康记录列表 -->
    <el-card class="health-records-card" v-if="selectedPetId">
      <div slot="header">
        <span>健康检测记录</span>
      </div>

      <el-timeline>
        <el-timeline-item
          v-for="record in healthRecords"
          :key="record.id"
          :timestamp="record.checkDate"
          placement="top"
          :color="getTimelineColor(record.status)">
          <el-card shadow="hover" class="record-card">
            <div class="record-header">
              <h3>{{ record.title }}</h3>
              <el-tag :type="getStatusType(record.status)">{{ record.status }}</el-tag>
            </div>
            <el-descriptions :column="3" border size="small" style="margin: 15px 0">
              <el-descriptions-item label="体重">{{ record.weight }}kg</el-descriptions-item>
              <el-descriptions-item label="体温">{{ record.temperature }}°C</el-descriptions-item>
              <el-descriptions-item label="心率">{{ record.heartRate }}次/分</el-descriptions-item>
            </el-descriptions>
            <div class="record-detail">
              <p><strong>检测项目：</strong>{{ record.items }}</p>
              <p><strong>检测结果：</strong>{{ record.result }}</p>
              <p v-if="record.suggestion"><strong>医生建议：</strong>{{ record.suggestion }}</p>
            </div>
            <div class="record-footer">
              <el-button type="text" size="small" @click="handleViewDetail(record)">
                <i class="el-icon-view"></i> 查看详情
              </el-button>
              <el-button type="text" size="small" v-if="record.reportUrl">
                <i class="el-icon-download"></i> 下载报告
              </el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div v-if="!healthRecords.length" class="empty-data">
        <i class="el-icon-folder-opened"></i>
        <p>暂无健康记录</p>
      </div>
    </el-card>

    <!-- 未选择宠物提示 -->
    <el-empty v-if="!selectedPetId" description="请先选择一只宠物查看健康档案"></el-empty>
  </div>
</template>

<script>
import { getHealthRecords, getHealthRecordDetail } from '@/api/health'
import { getMyPets } from '@/api/user'

export default {
  name: 'PetHealth',
  data () {
    return {
      loading: false,
      myPets: [],
      selectedPetId: null,
      healthSummary: {
        totalRecords: 0,
        lastCheckDate: '-',
        healthScore: 0,
        abnormalItems: 0
      },
      healthRecords: []
    }
  },
  created () {
    this.loadMyPets()
  },
  methods: {
    loadMyPets () {
      getMyPets().then(res => {
        if (res && res.data) {
          const data = res.data.list || res.data || []
          this.myPets = data.map(item => ({
            id: item.id,
            name: item.name,
            breed: item.breed || ''
          }))
          if (this.myPets.length > 0) {
            this.selectedPetId = this.myPets[0].id
            this.loadHealthRecords()
          }
        }
      }).catch(err => {
        console.error('加载我的宠物失败：', err)
      })
    },
    loadHealthRecords () {
      if (!this.selectedPetId) {
        return
      }
      this.loading = true
      getHealthRecords({
        petId: this.selectedPetId,
        pageNum: 1,
        pageSize: 100
      }).then(res => {
        this.loading = false
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          this.healthRecords = data.map(item => ({
            id: item.id,
            title: item.title || item.checkType || '健康检查',
            checkDate: item.checkDate || item.createTime || '',
            weight: item.weight || 0,
            temperature: item.temperature || 0,
            heartRate: item.heartRate || item.heartrate || 0,
            respiratoryRate: item.respiratoryRate || item.respiratoryrate || 0,
            symptoms: item.symptoms || '',
            diagnosis: item.diagnosis || '',
            treatment: item.treatment || '',
            veterinarian: item.veterinarian || '',
            items: item.items || item.checkItems || '',
            result: item.result || item.diagnosis || '',
            suggestion: item.suggestion || item.notes || item.treatment || '',
            status: this.getStatusText(item.healthStatus || item.status),
            reportUrl: item.reportUrl || ''
          }))
          // 计算统计信息
          this.healthSummary.totalRecords = this.healthRecords.length
          if (this.healthRecords.length > 0) {
            const lastRecord = this.healthRecords[0]
            this.healthSummary.lastCheckDate = lastRecord.checkDate.split(' ')[0] || '-'
          }
          this.healthSummary.abnormalItems = this.healthRecords.filter(r => r.status === '异常').length
          this.healthSummary.healthScore = this.healthSummary.abnormalItems === 0 ? 100 : Math.max(60, 100 - this.healthSummary.abnormalItems * 10)
        }
      }).catch(err => {
        this.loading = false
        console.error('加载健康记录失败：', err)
        this.$message.error({ message: '加载健康记录失败', duration: 800 })
      })
    },
    getStatusText (status) {
      const statusMap = {
        0: '正常',
        1: '健康',
        2: '一般',
        3: '需要关注',
        4: '异常'
      }
      return statusMap[status] || '正常'
    },
    handleViewDetail (record) {
      getHealthRecordDetail(record.id).then(res => {
        if (res && res.data) {
          const data = res.data
          this.$alert(`
            <h3>${data.title || record.title}</h3>
            <p><strong>宠物名称：</strong>${data.petName || ''}</p>
            <p><strong>检测时间：</strong>${data.checkDate || record.checkDate}</p>
            <p><strong>检测医生：</strong>${data.veterinarian || record.veterinarian || '未知'}</p>
            <p><strong>体重：</strong>${data.weight || record.weight}kg</p>
            <p><strong>体温：</strong>${data.temperature || record.temperature}°C</p>
            <p><strong>心率：</strong>${(data.heartRate || data.heartrate || record.heartRate)}次/分</p>
            <p><strong>呼吸频率：</strong>${(data.respiratoryRate || data.respiratoryrate || record.respiratoryRate || 0)}次/分</p>
            <p><strong>症状：</strong>${data.symptoms || record.symptoms || '无'}</p>
            <p><strong>诊断：</strong>${data.diagnosis || record.diagnosis || '无'}</p>
            <p><strong>治疗方案：</strong>${data.treatment || record.treatment || '无'}</p>
            <p><strong>医生建议：</strong>${data.notes || data.suggestion || record.suggestion || '无'}</p>
            <p><strong>下次检查：</strong>${data.nextCheckDate || '无'}</p>
          `, '健康记录详情', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          })
        } else {
          this.$alert(`
            <h3>${record.title}</h3>
            <p><strong>检测时间：</strong>${record.checkDate}</p>
            <p><strong>检测医生：</strong>${record.veterinarian || '未知'}</p>
            <p><strong>体重：</strong>${record.weight}kg</p>
            <p><strong>体温：</strong>${record.temperature}°C</p>
            <p><strong>心率：</strong>${record.heartRate}次/分</p>
            <p><strong>呼吸频率：</strong>${record.respiratoryRate || 0}次/分</p>
            <p><strong>症状：</strong>${record.symptoms || '无'}</p>
            <p><strong>诊断：</strong>${record.diagnosis || '无'}</p>
            <p><strong>治疗方案：</strong>${record.treatment || '无'}</p>
            <p><strong>医生建议：</strong>${record.suggestion || '无'}</p>
          `, '健康记录详情', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          })
        }
      }).catch(err => {
        console.error('加载详情失败：', err)
        this.$alert(`
          <h3>${record.title}</h3>
          <p><strong>检测时间：</strong>${record.checkDate}</p>
          <p><strong>检测医生：</strong>${record.veterinarian || '未知'}</p>
          <p><strong>体重：</strong>${record.weight}kg</p>
          <p><strong>体温：</strong>${record.temperature}°C</p>
          <p><strong>心率：</strong>${record.heartRate}次/分</p>
          <p><strong>呼吸频率：</strong>${record.respiratoryRate || 0}次/分</p>
          <p><strong>症状：</strong>${record.symptoms || '无'}</p>
          <p><strong>诊断：</strong>${record.diagnosis || '无'}</p>
          <p><strong>治疗方案：</strong>${record.treatment || '无'}</p>
          <p><strong>医生建议：</strong>${record.suggestion || '无'}</p>
        `, '健康记录详情', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        })
      })
    },
    getStatusType (status) {
      const typeMap = {
        '正常': 'success',
        '异常': 'danger',
        '待观察': 'warning'
      }
      return typeMap[status] || 'info'
    },
    getTimelineColor (status) {
      const colorMap = {
        '正常': '#67C23A',
        '异常': '#F56C6C',
        '待观察': '#E6A23C'
      }
      return colorMap[status] || '#909399'
    }
  }
}
</script>

<style scoped>
.pet-health-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: white;
  border-radius: 8px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.pet-selector-card {
  margin-bottom: 20px;
  text-align: center;
}

.info-card {
  margin-bottom: 20px;
}

.info-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.info-icon {
  font-size: 40px;
}

.info-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.info-label {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
}

.health-records-card {
  margin-top: 20px;
}

.record-card {
  margin-top: 10px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.record-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.record-detail {
  margin: 15px 0;
}

.record-detail p {
  margin: 8px 0;
  color: #666;
  line-height: 1.6;
}

.record-footer {
  display: flex;
  gap: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.empty-data {
  text-align: center;
  padding: 50px;
  color: #999;
}

.empty-data i {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-data p {
  font-size: 16px;
}
</style>
